/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package biz;

import da.NewsJpaController;
import da.exceptions.PreexistingEntityException;
import da.exceptions.RollbackFailureException;
import entities.News;
import java.util.LinkedList;
import java.util.List;
import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.persistence.TypedQuery;
import javax.transaction.UserTransaction;

/**
 *
 * @author THOHCGC00177
 */
@Stateless
@TransactionManagement(TransactionManagementType.BEAN)
public class NewsProgess {

    @Resource
    private UserTransaction utx;
    @PersistenceUnit(unitName = "ProjectSem4PU")
    private EntityManagerFactory emf = null;
    private NewsJpaController jpa;

    public NewsJpaController getJpa() {
        if (jpa == null) {
            jpa = new NewsJpaController(utx, emf);
        }
        return jpa;
    }
    /**
     * 
     * Function get all news 
     * @return 
     */
    public List<News> getAllNews() {
        return getJpa().findNewsEntities();
    }

    public void createNews(News news) throws PreexistingEntityException, RollbackFailureException, Exception {
        getJpa().create(news);
    }
    /**
     * 
     * Function get news with length
     * @return 
     */
    public List<News> getNewsForIndex() {
        List<News> list = new LinkedList<News>();
        List<News> lists = getJpa().findNewsEntities();
        int lengt = lists.size();
        for (int i = lengt - 1; i > lengt - 4; i--) {
            News item = lists.get(i);
            list.add(item);
        }
        return list;
    }
    public News getNewsById(int id) {
        String query = "SELECT n FROM News n WHERE n.id = :id";
        TypedQuery<News> tq = emf.createEntityManager().createQuery(query, News.class);
        tq.setParameter("id", id);
        try {
            return tq.getSingleResult();
        } catch (Exception e) {
            return null;
        }
    }
}
